package com.sunday.shoufen.ui.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.base.BaseLazyFragment;
import com.sunday.shoufen.entity.CouponBalance;
import com.sunday.shoufen.entity.RecordDetail;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.SearchMemberActivity;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.common.widgets.EmptyLayout.HIDE_LAYOUT;
import static com.sunday.common.widgets.EmptyLayout.NODATA;

/**
 * Created by 刘涛 on 2017/10/25.
 */

public class CouponListFragment extends BaseLazyFragment {
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;


    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<RecordDetail> dataSet = new ArrayList<>();
    private CommonAdapter<RecordDetail> adapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private int sort;


    public static CouponListFragment newInstance(int sort) {
        CouponListFragment fragment = new CouponListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("sort", sort);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            sort = getArguments().getInt("sort");
        }
    }

    public int getSort() {
        return sort;
    }

    public void setSort(int sort) {
        this.sort = sort;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.layout_fragment_recycler, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;
        memberId = BaseApp.getInstance().getMember().getId();
        getData();
    }


    private void initRefreshLayout() {
        adapter = new CommonAdapter<RecordDetail>(mContext, R.layout.list_coupon_balance_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, RecordDetail detail) {
                bind(holder, detail);
            }
        };
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (isCanloadMore) {
                    pageNo++;
                    getData();
                } else {
                    refreshlayout.finishLoadmore();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNo = 1;
                getData();
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });
    }

    private void bind(ViewHolder holder, final RecordDetail recordDetail) {
        TextView score = holder.getView(R.id.money);
        TextView time = holder.getView(R.id.time);
        TextView from = holder.getView(R.id.from);
        ImageView imgExpired = holder.getView(R.id.img_expired);
        TextView btnGive = holder.getView(R.id.btn_give);

        score.setText(recordDetail.getAmount().setScale(2, RoundingMode.HALF_UP) + "");
        time.setText("有效期" + recordDetail.getTime());
        from.setText(recordDetail.getMemo());
        switch (recordDetail.getStatus()) {
            case 0:
                imgExpired.setVisibility(View.GONE);
                btnGive.setText("转赠");
                btnGive.setVisibility(View.VISIBLE);
                break;
            case 1:
                imgExpired.setVisibility(View.GONE);
                btnGive.setVisibility(View.VISIBLE);
                btnGive.setText("已转赠");
                break;
            case 2:
                imgExpired.setVisibility(View.VISIBLE);
                btnGive.setVisibility(View.GONE);
                break;
            case 3:
                imgExpired.setVisibility(View.GONE);
                btnGive.setVisibility(View.VISIBLE);
                btnGive.setText("已使用");
                break;
            default:
                imgExpired.setVisibility(View.GONE);
                btnGive.setVisibility(View.GONE);
        }

        holder.setOnClickListener(R.id.btn_give, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (recordDetail.getStatus()) {
                    case 0:
                        intent = new Intent(mContext, SearchMemberActivity.class);
                        intent.putExtra("ticketId", recordDetail.getId());
                        startActivity(intent);
                        break;
                }

            }
        });


    }

    private void getData() {
        Call<ResultDO<List<RecordDetail>>> call = ApiClient.getApiAdapter().getTicketFeeDetail(memberId, pageNo, Constants.PAGE_SIZE, sort);
        call.enqueue(new Callback<ResultDO<List<RecordDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<RecordDetail>>> call, Response<ResultDO<List<RecordDetail>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                refreshLayout.finishLoadmore();
                refreshLayout.finishRefresh();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    emptyLayout.setErrorType(dataSet.size() > 0 ? HIDE_LAYOUT : NODATA);
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<RecordDetail>>> call, Throwable t) {
                refreshLayout.finishLoadmore();
                refreshLayout.finishRefresh();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()){
            pageNo=1;
            getData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
